// *******************************************************************************************************
// # INDEX
//   / トップ
// *******************************************************************************************************
this.rjapmn = this.rjapmn || {};

(function(){
	rjapmn.data = {};

	//DEBUG
	rjapmn.data.is_debug = false;

	//賃貸物件検索メニュー
	//<li id="area">or<li id="shop">、どちらかに付加されるid="actived"に合わせて
	//rjapmn.data.typeに値を代入する
	rjapmn.data.type = "area";

	//chara
	rjapmn.data.json_chara = "";
	rjapmn.data.charaRandomNumArray = [];
	rjapmn.data.charaMaxNum = 0;
	rjapmn.data.charaNum = 0;

	//ie6判定
	rjapmn.data.ie6 = (uaInfo.isIe && uaInfo.ieVr <= 6) ? true : false;

	//pjax easing interval
	rjapmn.data.INTERVAL = 200;

	//bxslider
	rjapmn.data.BxSlider_SPEED = 800;
	rjapmn.data.BxSlider_PAUSE = 5000;

	rjapmn.data.btnShowArray = [
		"/static/top/images/btn_area_search_off.png",
		"/static/top/images/btn_area_search_on.png",
		"/static/top/images/btn_shop_search_off.png",
		"/static/top/images/btn_shop_search_on.png"
	];

	//chara_json
	rjapmn.data.PATH_CHARA_JSON = "/static/top/json/chara_comment.json";

	rjapmn.data.is_firstvisit = true;

	function update_todofuken_links($this) {
		var area_shop = $this.attr('id');
		$('a.todofuken').each(function(index,elem) {
			var $elem = $(elem);
			var url=$elem.attr('href');
			url = url.replace(/shop\/$/,"");
			if (area_shop=='shop') url+='shop/';
			$elem.attr('href',url);
		});
	}

	//----------------------------------------------------------------------------
	// INIT - Event
	//----------------------------------------------------------------------------
	rjapmn.init = function(){

		rjapmn.setFilterPngForIE();
		rjapmn.checkDebugMode();

		rjapmn.initEvent("load");

		//bxslider
		rjapmn.initBxSlider();
	}

	rjapmn.initEvent = function(str){
		switch(str){
			case "load":
				rjapmn.onLoadMainEvent();
			break;
			
			case "cookie_areatype":
				rjapmn.initCookieAreaType();
			break;

			case "showBtnSearch":
				//home.css 96line
				//#contentsTopInner .tab_contents .btn_col{opacity:0}
				rjapmn.showBtnSearch();
			break;
			
			case "btn":
				rjapmn.initBtnMap();
				rjapmn.initBtnSearch();

				rjapmn.initEvent("cookie_visit");
			break;

			case "cookie_visit":
				rjapmn.initCookieVisit();
			break;

			case "load_json":
				//chara
				rjapmn.onLoadJsonCharaComment("init");

			break;
		}
	}

	rjapmn.onLoadJsonCharaComment = function(str){
		var _slice = str.slice(0, 1);

		if(str == "init"){
			rjapmn.loadDataUtil.onGet("json", rjapmn.data.PATH_CHARA_JSON, rjapmn, "onLoadDataUtilComplete");

		// pjaxでTOP(全国)に戻ってきた場合
		}else if(_slice == "/"){
			rjapmn.onCharaCommentControll();
		}
	}

	//----------------------------------------------------------------------------
	// MODAL
	//----------------------------------------------------------------------------
	rjapmn.createFirstVisitModal = function(e){
		$('html,body').stop().animate({ scrollTop: 0 }, 1 );
		modalAreaAddOrDelete.alpha(0.8);
		modalAreaAddOrDelete.show();
	}

	// 追加・削除
	var modalAreaAddOrDelete = (function(){
		var that = {
			modal: null,
			defInput: []
		};
		function init(){
			that.modal = new APMN.Modal({
				target: $('#modal_firstvisit_area'),
				close:  $('#modal_firstvisit_area .modal_close'),
				ieVr: !(rjapmn.data.ie6)
			});

/*			$('#modal_result_area .mod_btn_append a').on('click', function(e){
			});*/

			$("#modal_firstvisit_area .modal_close a img") .hover(function(){
				$(this).css('opacity', '0.7');
			},function(){
				$(this).css('opacity', '1');
			});

			$('#modal_firstvisit_area .modal_close a').on('click', function(e){

				e.preventDefault();

				$('#modal_firstvisit_area .cnt-modal').remove();
				$('#modal_firstvisit_area').prepend('<div class="cnt-modal"></div>');

				/*that.modal.hide();*/
			});
		};

		that.show = function(){
			rjapmn.onLoadingEvent.start();

			that.modal.show();
			rjapmn.onLoadFirstModalHtml();
		};
		
		that.hide = function(){
			that.modal.hide();
		};

		that.alpha = function(num){
			that.modal.alpha(num);
		};

		init();
		return that;
	}());

	rjapmn.onLoadFirstModalHtml =function(){
		//$('#modal_firstvisit_area .cnt-modal').load('/static/top/modal/modal.html');
		$('#modal_firstvisit_area .cnt-modal').load('/topmodal/modal/');
		
		window.setTimeout(function(){
			$('#modal_firstvisit_area #modal_loader').stop();
			$('#modal_firstvisit_area #modal_loader').remove();			
		}, 2000);
	}

	/*モーダルから呼び出されます*/
	rjapmn.onLoadingEvent = {
		start:function(){
			$('#modal_firstvisit_area').prepend('<div id="modal_loader"><img src="/static/top/modal/images/loader.gif" width="60" height="60" alt="loader" /></div>');
			
			$('#modal_firstvisit_area #modal_loader')
			.delay(400)
			.animate({opacity:1}, 10, "easeOutQuart");
		},
		complete:function(){
			$('#modal_firstvisit_area #modal_loader').stop();
			$('#modal_firstvisit_area #modal_loader').remove();
/*			$('#modal_firstvisit_area #modal_loader')
			.animate({opacity:0}, 100, "easeOutQuart", function() {
				$('#modal_loader').remove();
			});*/
		}
	}

	//----------------------------------------------------------------------------
	// INIT - Cookie Visit
	//----------------------------------------------------------------------------
	rjapmn.initCookieVisit = function(){

		if (navigator.cookieEnabled) {

			var _cookie = rjapmn.getCookie("rjapmnvisit");

			if(_cookie){
				rjapmn.data.is_firstvisit = false;
			}else{
				rjapmn.data.is_firstvisit = true;
				rjapmn.setCookie("rjapmnvisit", 1);
			}

			rjapmn.initEvent("load_json");
		}
	}

	//----------------------------------------------------------------------------
	// INIT - Cookie Areatype
	//----------------------------------------------------------------------------
	rjapmn.initCookieAreaType = function(){

		if (navigator.cookieEnabled) {

			var i, _class, _img;

			var _cookie = rjapmn.getCookie("rjapmn");
			var _li = $('#search-area li');
			var _len = _li.length;

			if(_cookie){

				//cookieが保持する値の<li>に、id="actived"を付加。
				//IEは、各HTMLのactivedが違う時があるから、一度、全部のliのactivedを削除
				_li.removeClass("actived");

				for(i=0;i<_len; i++){
					_class = $('#search-area li:eq('+i+')');

					if(_cookie == _class.attr("id")){
						_class.addClass("actived");
					}
				}

				for(i=0; i<_len; i++){
					_class = $('#search-area li:eq('+i+')');
					_img = $('#search-area li:eq('+i+') img');

					if(_cookie == _class.attr("id")){
						rjapmn.onImgReplace.on(_img);

						rjapmn.onContentEvent(_cookie);

					}else{
						rjapmn.onImgReplace.off(_img);
					}
				}

			}else{

				//HTMLに記述にそったid="actived"を実行
				for(i=0; i<_len; i++){
					_class = $('#search-area li:eq('+i+')');
					_img = $('#search-area li:eq('+i+') img');

					if(_class.hasClass('actived')){
						rjapmn.onImgReplace.on(_img);

						rjapmn.onContentEvent(_class.attr('id'));

					}else{
						rjapmn.onImgReplace.off(_img);
					}
				}
			}

		}else {
			//You can't cookie
		}

		rjapmn.initEvent("showBtnSearch");
	}

	rjapmn.setCookie = function(str, obj){
		var cookieName = str+'=';
		document.cookie =cookieName + obj + '; path=/' + rjapmn.createCookiDate(1);
	}

	rjapmn.getCookie = function(str){
		var result = null;
		var cookieName=str+'=';
		var rjcookie = document.cookie;

		var cookieData = rjcookie.indexOf(cookieName);

		if(cookieData != -1){
			var startIndex = cookieData + cookieName.length;
			var endIndex = rjcookie.indexOf(';',startIndex);

			if(endIndex == -1){
				endIndex = rjcookie.length;
			}
			result = decodeURIComponent(rjcookie.substring(startIndex, endIndex));
		}
		return result;
	}

	rjapmn.createCookiDate = function(dir){
		var str="";
		var expires;
		var nowtime = new Date().getTime();
		
		expires = new Date(nowtime + (60 * 60 * 24 * 1000 * 3 * dir));
		
		expires = expires.toGMTString();
		str += "; expires=" + expires;
		return str;
	}

	rjapmn.deleteCookie = function(obj) {
		cName = obj+'=';
		document.cookie = cName  + rjapmn.createCookiDate(-1);
	}

	//----------------------------------------------------------------------------
	// INIT - BtnMap
	//----------------------------------------------------------------------------
	rjapmn.initBtnMap = function(){

		//init rollover
		rjapmn.initRollOverReplace('#contentsTopInner .tab_contents .maparea li a img');
		rjapmn.initRollOverReplace('#contentsTopInner .tab_contents li.btn_easyrequest a img');
		
/*		//init 2ステップで！簡単リクエスト
		//rjapmn.initRollOverReplace('#contentsTopInner .tab_contents li.btn_easyrequest a img');
		$(".btn_easyrequest .btn_easyrequest_core a").hover(
			function () {
				$(".btn_easyrequest .btn_easyrequest_core img").css({marginTop:300});
				//$(this).stop().animate({backgroundPosition:"0px 274px"},{duration:10});
				$(this).css({backgroundPosition:"0px 0px"});
			},
			function () {
				$(".btn_easyrequest .btn_easyrequest_core img").css({marginTop:0});
				//$(this).stop().animate({backgroundPosition:"0px 0px"},{duration:10});
				$(this).css({backgroundPosition:"0px 274px"});
			}
		);
		// /init 2ステップで！簡単リクエスト*/

/*		$('.btn_easyrequest .btn_easyrequest_core a').append(
			'<img class="png btn_easyrequest_on" src="/static/top/images/btn_bear_search_on.png" width="287" height="274" alt="2ステップで！かんたんリクエスト　非公開物件や掲載前の物件も！！　今すぐチェック">'
		);

		$(".btn_easyrequest .btn_easyrequest_core a").hover(
			function () {
				$("img:eq(0)",this).css({opacity:0});
				$("img:eq(1)",this).css({opacity:1});
			},
			function () {
				$("img:eq(0)",this).css({opacity:0});
				$("img:eq(1)",this).css({opacity:1});
			}
		);*/


		//init pjax
		$(document).on('click', 'a.pjax', function(e) {

			//ie6の場合、推移先のURLの最後に?が付加される不具合があるので、
			//判別して、pjaxを動作させない。
			if(!rjapmn.data.ie6){
				e.preventDefault();
				rjapmn.data.href = $(this).attr('href');

				$('#area_search').animate({
					opacity : 0
				}, rjapmn.data.INTERVAL, 'easeOutQuad', function() {
					$.pjax({
						url: rjapmn.data.href,
						container : '#area_search',
						fragment : '#area_search',
						timeout : 30000
					});
				});
			}
		});

		//end pjax
		$(document).on('pjax:end', function() {
			$('#area_search').animate({
				opacity : 1
			}, rjapmn.data.INTERVAL, 'easeOutQuad', function() {
				rjapmn.onLoadJsonCharaComment(rjapmn.data.href);
				rjapmn.initRollOverReplace('#contentsTopInner .tab_contents .maparea li a img');
			});
			update_todofuken_links($('#search-area li.actived'));
		});
	}

	//----------------------------------------------------------------------------
	// INIT - RollOver Replace
	//----------------------------------------------------------------------------
	rjapmn.initRollOverReplace = function(str){
		$(str).hover(function(){
			rjapmn.onImgReplace.on($(this));
		}, function(){
			rjapmn.onImgReplace.off($(this));
		});
	}

	//----------------------------------------------------------------------------
	// INIT - BtnSearch
	//----------------------------------------------------------------------------
	rjapmn.initBtnSearch = function(){
		//hover
		$('#search-area li').hover(function(){

			if (!$(this).hasClass('actived')) {

				$(this).css({opacity:'0.8'});
			}
		}, function(){

			$(this).css({opacity:'1'});
		});

		//click
		var _li = $('#search-area li');
		_li.on('click', function (e) {

			/*e.preventDefault();*/

			var is_class= $(this).hasClass("actived");

			if(!is_class){
				_li.removeClass("actived");
				$(this).addClass("actived");

				$(this).css({opacity:'1'});

				var _len = _li.length;
				for(var i=0; i<_len; i++){
					var _img = $('#search-area li:eq('+i+') img');
					rjapmn.onImgReplace.off(_img);

				}

				rjapmn.onImgReplace.on($('img',this));

				rjapmn.onContentEvent($(this).attr("id"));
				
				update_todofuken_links($(this));
			}
		});
		update_todofuken_links($('#search-area li.actived'));
		
		//スマホの場合
		if(window.location.href.indexOf('?s') > 0){
			$('#search-area').find('#shop').trigger('click');
		}
	}

	//----------------------------------------------------------------------------
	// EVENT - BtnSearch
	//----------------------------------------------------------------------------
	rjapmn.showBtnSearch = function(){
		$("#contentsTopInner .tab_contents .btn_col").css({
			opacity:1
		})

		rjapmn.initEvent("btn");
	}

	//----------------------------------------------------------------------------
	// EVENT - SEARCH TYPE
	//----------------------------------------------------------------------------
	rjapmn.getSearchType = function(){
		return rjapmn.data.type;
	}

	rjapmn.onContentEvent = function(str){
		rjapmn.dataType.set(str);
		rjapmn.setCookie('rjapmn', rjapmn.dataType.get());
		//console.log("str=="+str);
		//alert("type="+rjapmn.dataType.get());
	}

	rjapmn.dataType = {
		set:function(str){rjapmn.data.type=str;},
		get:function(){return rjapmn.data.type;}
	}

	rjapmn.onImgReplace = {
		on:function(obj){obj.attr('src', obj.attr('src').replace('_off', '_on'));},
		off:function(obj){obj.attr('src', obj.attr('src').replace('_on', '_off'));}
	}

	rjapmn.onLoadMainEvent = function(){
		var len = rjapmn.data.btnShowArray.length;
		rjapmn.data.loadcount = len;

		for(var i=0; i<len; i++){
			rjapmn.loaderUtil.init(i, rjapmn.data.btnShowArray[i], rjapmn, "onLoadMainComplete");
		}
	}

	rjapmn.onLoadMainComplete = function(){
	    	rjapmn.data.loadcount--;
	    	if(rjapmn.data.loadcount == 0){
	    		rjapmn.initEvent("cookie_areatype");
	    	}
	}

	rjapmn.loaderUtil={
		_scope:[],
		_callback:"",
		_imgArray:[],
		
		init:function(num,url,scope,func){
			this._scope[0]=scope;
			this._callback=func;
			this._imgArray[num]=new Image();
			this._imgArray[num].onload=rjapmn.loaderUtil.onComplete;
			this._imgArray[num].src=url;
		},

		onComplete:function(){
			(function(){rjapmn.loaderUtil._scope[0][rjapmn.loaderUtil._callback]()})();
		}
	}

	//----------------------------------------------------------------------------
	// EVENT - Create comment
	//----------------------------------------------------------------------------
	rjapmn.onAnalysisCharaJson = function(data){
		rjapmn.data.json_chara = data;
		rjapmn.data.charaMaxNum = data.length;
		var ary = [];

		if(rjapmn.data.charaMaxNum > 1){
			//json初段の初訪問コメントを除いてランダムに
			for(var i=0; i<rjapmn.data.charaMaxNum-1; i++){
				ary[i] = i;
			}
			rjapmn.data.charaRandomNumArray = ary.shuffle();
		}
		rjapmn.onCharaCommentControll();
	}

	rjapmn.onCharaCommentControll = function(){
		rjapmn.createCharaComment(rjapmn.data.charaRandomNumArray[rjapmn.data.charaNum]);
		if(rjapmn.data.charaMaxNum > 1){
			rjapmn.data.charaNum++;
			if(rjapmn.data.charaNum >= rjapmn.data.charaMaxNum-1){
				rjapmn.data.charaNum = 0;
			}	
		}
	}
	
	rjapmn.createCharaComment = function(num){
		//var num = 0;
		var htmlSouce = "";

		if(rjapmn.data.is_firstvisit){
			num = 0;
			rjapmn.data.is_firstvisit = false;

			htmlSouce = rjapmn.getHtmlCharaFirstCommentSource(rjapmn.data.json_chara[num]["url"], rjapmn.data.json_chara[num]["comment"]);
		}else{
			num = num+1;
			htmlSouce = rjapmn.getHtmlCharaCommentSource(rjapmn.data.json_chara[num]["url"], rjapmn.data.json_chara[num]["target"], rjapmn.data.json_chara[num]["comment"]);
		}

		$('.tab_contents .bear_jp').append(htmlSouce);
	}

	rjapmn.getHtmlCharaFirstCommentSource = function(_url, _com){
		var _source="";
		_source +='<div class="firstcomment">'
		_source +='<a class="png" href="javascript:void(0)" onclick="rjapmn.createFirstVisitModal(); return false;">';
		_source += _com;
		_source += '</div>';
		_source += '</a>';

		return _source;
	}

	rjapmn.getHtmlCharaCommentSource = function(_url, _target, _com){
		var _source="";
		_source +='<div class="comment">'
		_source +='<a class="png" href="'+_url+'" target="'+_target+'">';
		_source += _com;
		_source += '</div>';
		_source += '</a>';

		return _source;
	}

	//----------------------------------------------------------------------------
	// LOAD - JSON
	//----------------------------------------------------------------------------
	rjapmn.onLoadDataUtilComplete = function(data){
		//console.log("data="+data[1]["url"]);
		//console.log("data="+data.length);

		rjapmn.onAnalysisCharaJson(data);
	}

	rjapmn.loadDataUtil = {
		_scope:[],
		_callback:[],

		onGet:function(sDataType, sUrl, oScope, sCallback){
			var _obj = {};
			if(oScope)this._scope[0] = oScope;
			if(sCallback)this._callback[0] = sCallback;
			//var nocacheUrl = sUrl+"?"+parseInt((new Date)/1000);
			_obj = {
				type:"GET",
				dataType:sDataType,
				url:sUrl,
				cache:false,
				timeout:2000,
				success:rjapmn.loadDataUtil.onSuccess,
				error:rjapmn.loadDataUtil.onError,
				complete:rjapmn.loadDataUtil.onComplete
			}
			jQuery.ajax(_obj);
		},
		onSuccess: function(data, status){
			if(status != 'success')return;
			(function(){rjapmn.loadDataUtil._scope[0][rjapmn.loadDataUtil._callback[0]](data)})();
		},
		onError:function(XMLHttpRequest, textStatus, errorThrown){
			console.log("LoadData-Error/textStatus="+textStatus);
		},
		onComplete:function(XMLHttpRequest, textStatus){
		}
	}

	Array.prototype.shuffle = function(){
		var i = this.length;
		while(i){
			var j = Math.floor(Math.random()*i);
			var t = this[--i];
			this[i] = this[j];
			this[j] = t;
		}
	    	return this;
	}


	rjapmn.checkDebugMode = function(){
		if(rjapmn.data.is_debug){
			var htmlSouce = rjapmn.getFirstVisitClearText();
			$('.tab_contents .bear_jp').prepend(htmlSouce);
		}else{

		}
	}

	rjapmn.getFirstVisitClearText = function(){
		var _source="";
		_source +='<div id="btn-cookieclear">';
		_source +='<a href="javascript:rjapmn.clearCookieFirstVisit()">';
		_source +='初回訪問Cookieクリア';
		_source += '</a>';
		_source += '</div>';

		return _source;
	}

	rjapmn.clearCookieFirstVisit = function(){
		rjapmn.deleteCookie("rjapmnvisit");
		CONS.clearCookie();
		window.location.reload();
	}


	//----------------------------------------------------------------------------
	// INIT - BxSlider
	//----------------------------------------------------------------------------
	rjapmn.initBxSlider = function(){
		if(!rjapmn.data.ie6){
			$('.bxslider').bxSlider({
				auto: true,
				mode: 'horizontal',
				pause: rjapmn.data.BxSlider_PAUSE,
				speed: rjapmn.data.BxSlider_SPEED
			});
		}
	}

	/*IE8対応　透過PNG*/
	rjapmn.setFilterPngForIE = function(){
		$('.btn_bear img').each(function() {
			if($(this).attr('src').indexOf('.png') != -1) {
				$(this).css({
					'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + $(this).attr('src') + '", sizingMethod="scale");'
				});
			}
		});
	}
})();

//----------------------------------------------------------------------------
// INIT
//----------------------------------------------------------------------------
$(document).ready(
	function(){
		rjapmn.init();				
	}
);

